package com.example.reader.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.example.reader.entity.Account;
import com.example.reader.entity.Comment;
import com.example.reader.mapper.CommentMapper;
import com.example.reader.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletionException;

/**
 * 业务层方法
 */
@Service
public class CommentService {

    @Resource
    private CommentMapper commentMapper;
    public Integer selectCount(String module, Integer fid) {
        return commentMapper.selectCount(module, fid);
    }

    public PageInfo<Comment> selectTree(String module, Integer fid, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> rootList = commentMapper.selectByModuleAndFid(module, fid);
        for (Comment root : rootList) {
            Integer rootId = root.getRootId();
            List<Comment> children = commentMapper.selectByRootId(rootId);
            root.setChildren(children);
        }
        return PageInfo.of(rootList);
    }


    //递归删除
    public void deepDelete(Integer id) {
        commentMapper.deleteById(id);
        List<Comment> children = commentMapper.selectByPid(id);// 再递归删除子评论
        if (children != null && children.size() != 0) {
            System.out.println(children != null && children.size() != 0);
            for (Comment child : children) {
                this.deepDelete(child.getId());
            }
        }
    }

    //评论
    public void add(Comment comment) {
        Account currentUser = TokenUtils.getCurrentUser();
        comment.setUserId(currentUser.getId());
        comment.setTime(DateUtil.now());
        commentMapper.insert(comment);
        Comment comment1 =commentMapper.newcomment(comment);
        Integer id=comment1.getId();
        comment.setRootId(id);
        comment.setId(id);
        if (comment.getPid() == null) {  // 最外层的评论
            comment.setRootId(id);
        } else {  // 回复的评论
            Integer pid = comment.getPid();
            Comment pComment = commentMapper.selectById(pid);  // 父级评论
            comment.setRootId(pComment.getRootId());
        }
        commentMapper.updateById(comment);
    }

    //分页查询
    public PageInfo<Comment> selectPage(Comment comment, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> list = commentMapper.selectAll(comment);
        return PageInfo.of(list);
    }
}
